<template>
  <!-- 页面-分配角色 -->
  <div class="run-mod-box" style="overflow: auto;">
    <InnerPageTable ref="roleTable" :config="tableConfig">
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="common" :text="$t('module.role.assignRole')" :disabled="orgId == ''" @click="assignRole" />
        <RPButton optType="batch" @click="deleted()" />
      </div>
    </InnerPageTable>
  </div>
</template>
<script>
import { CoreModuleName } from '@/const.js'
import orgAssignRoleAPI from '@/api/orgAssignRoleAPI.js'
import valueSetAPI from '@/api/valueSetAPI.js'
// import { orgAssignRoleColumns } from "./columns.js";
import OrgSelectRole from './OrgSelectRole.vue'
import RoleAssignUser from './RoleAssignUser.vue'
import locales from './locales.js'

import DataAccess from './DataAccess.vue' // 数据权限

const ASSIGNMENT_TYPE_ASSIGN_USER = 3
const ALLOCATION_TYPE_BY_ADMIN = 1
export default {
  mixins: [locales],
  components: { RoleAssignUser },
  props: {
    topNode: {
      type: Boolean,
      default() {
        return false
      }
    },
    orgData: {
      type: Array,
      default() {
        return []
      }
    },
    orgId: {
      type: String,
      default() {
        return ''
      }
    },
    orgPath: {
      type: String,
      default() {
        return ''
      }
    },
    orgName: String
  },
  data() {
    return {
      category: 1,
      tenantCode: '',
      tableData: [],
      managementTypeList: {}, // 权限类型数据
      assignmentTypeList: {} // 用户分配模式数据
    }
  },
  computed: {
    tableConfig() {
      // loadDataFn: ({ responseProcess, param }) => {
      //   orgAssignRoleAPI.queryAssignedRole(this.orgId).then(data => {
      //     responseProcess(data);
      //   });
      // },
      // initParam: { orgId: this.orgId },
      return {
        resource: this.tableData,
        // columnsFn: orgAssignRoleColumns.bind(this),
        columnsFn: this.orgAssignRoleColumns,
        isPage: false,
        autoFirst: false,
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    }
  },
  created: function() {
    this.init()
  },
  mounted: function() {},
  methods: {
    // 自定义行样式
    rowClassName(row) {
      //enabled:1-有效；0-无效
      let effectiveTime = this.$root.$options.filters['effective-time'](row.effectBegin, row.effectEnd)
      if (row.enabled == 0 || effectiveTime == false) {
        return 'tableDisableStyle'
      }
    },
    // // 自定义行样式
    // rowClassName(row) {
    //   // enabled: 无效：0 有效：1
    //   let enabled = row.enabled;
    //   let effectBegin = row.effectBegin;
    //   let effectEnd = row.effectEnd;
    //   let effectiveTime =
    //     effectBegin && effectEnd
    //       ? this.curDate() >= effectBegin && this.curDate() <= effectEnd
    //       : effectBegin
    //       ? this.curDate() >= effectBegin
    //       : effectEnd
    //       ? this.curDate() <= effectEnd
    //       : true;
    //   // 无效为0 || 不在有效时间内为false，需灰化
    //   if (enabled == 0 || effectiveTime == false) {
    //     return "tableDisableStyle";
    //   }
    // },
    // // 当前时间
    // curDate() {
    //   var time = new Date();
    //   var Y = time.getFullYear() + "-";
    //   var M = this.addZero(time.getMonth() + 1) + "-";
    //   var D = this.addZero(time.getDate()) + " ";
    //   var h = this.addZero(time.getHours()) + ":";
    //   var m = this.addZero(time.getMinutes()) + ":";
    //   var s = this.addZero(time.getSeconds());
    //   return Y + M + D + h + m + s;
    // },
    // // 补零
    // addZero(num) {
    //   return num < 10 ? "0" + num : num;
    // },
    orgAssignRoleColumns() {
      const COLUMN_WIDTH = window.RPConfig.COLUMN_WIDTH
      return [
        {
          type: 'selection',
          width: 45,
          align: 'center'
        },
        {
          type: 'expand',
          width: 45,
          align: 'center',
          render: (h, params) => {
            return h(RoleAssignUser, {
              props: {
                topNode: this.topNode,
                category: this.category,
                roleCode: params.row.roleCode,
                tenantCode: this.tenantCode,
                orgId: this.orgId,
                roleId: params.row.roleId,
                orgName: this.orgName,
                orgRoleId: params.row.orgRoleId,
                roleCode: params.row.roleCode,
                roleName: params.row.roleName
              }
            })
          }
        },
        {
          title: this.$t('module.role.roleCode'),
          key: 'roleCode',
          minWidth: 180,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.roleCode
                }
              },
              params.row.roleCode
            )
          }
        },
        {
          title: this.$t('module.role.roleName'),
          key: 'roleName',
          minWidth: 180,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.roleName
                }
              },
              params.row.roleName
            )
          }
        },
        {
          title: this.$t('common.status'),
          key: 'enabled',
          align: "center",
          minWidth: 80,
          maxWidth: 80 + COLUMN_WIDTH.MAX_WIDTH_MORE,
          render: (h, params) => {
            return h(
              'StatusButton',
              {
                // 修改StatusButton内容居中
                style: {
                  "justify-content": "center"
                },

                props: {
                  status: params.row.enabled == 1 ? '0' : '1'
                }
              },
              params.row.enabled ? this.$t('common.enable') : this.$t('common.disable')
            )
          }
        },
        {
          title: this.$t('module.role.accessType'),
          key: 'managementType',
          align: "center",
          minWidth: COLUMN_WIDTH.COLUMN_WIDTH_8_WORDS,
          maxWidth: COLUMN_WIDTH.COLUMN_WIDTH_8_WORDS + COLUMN_WIDTH.MAX_WIDTH_MORE,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: this.managementTypeList[params.row.managementType + '']
                }
              },
              this.managementTypeList[params.row.managementType + '']
            )
          }
        },
        {
          title: this.$t('module.role.assignmentType'),
          key: 'assignmentType',
          minWidth: 190,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: this.assignmentTypeList[params.row.assignmentType + '']
                }
              },
              this.assignmentTypeList[params.row.assignmentType + '']
            )
          }
        },
        {
          title: this.$t('common.operating'),
          align: 'left',
          fixed: 'right',
          width: 55,
          render: (h, params) => {
            return h('RowTools', {
              props: {
                data: [
                  {
                    type: 'icon',
                    icon: 'ios-settings',
                    text: this.$t('module.role.dataAccess'),
                    hidden: params.row._disabled,
                    handle: () => {
                      this.setPermissions(params.row)
                    }
                  },
                  {
                    type: 'icon',
                    icon: 'ios-eye',
                    text: this.$t('common.detail'),
                    hidden: !params.row._disabled,
                    handle: () => {
                      this.setPermissions(params.row, true)
                    }
                  }
                ]
              }
            })
          }
        }
      ]
    },
    init() {
      // 当前租户
      let { userInfo } = $store.state[CoreModuleName]
      if (!userInfo) return
      this.tenantCode = userInfo.tenantCode
      this.category = userInfo.category
      // 初始化管理权限
      this.initManagementType()
      // 初始化用户分配模式
      this.initAssignmentType()
    },
    search(page) {
      let params = {
        orgId: this.orgId
      }
      orgAssignRoleAPI.queryAssignedRole(params).then(data => {
        data.forEach(role => {
          if (role.assignmentType != ASSIGNMENT_TYPE_ASSIGN_USER) {
            role._disableExpand = true
          }
          // 平台管理员授权给租户管理员的角色不允许租户删除分配关系
          if (role.allocationType == ALLOCATION_TYPE_BY_ADMIN) {
            role._disabled = true
          }

          /* 1.组织树顶级节点 2.所分配角色是平台默认分配的平台管理员角色
           * 不可删除
           */
          if (this.topNode && this.category == '1' && role.roleCode == 'admin-dadp') {
            role._disabled = true
          }
        })
        this.tableData = data
      })
    },
    assignRole() {
      new this.$pageModal(
        OrgSelectRole,
        {
          props: {
            tenantCode: this.tenantCode,
            orgId: this.orgId,
            orgPath: this.orgPath
          }
        },
        data => {
          data && this.search()
        }
      )
    },
    deleted() {
      let selectedIds = this.getSelectedIds()
      if (selectedIds.length == 0) {
        this.$message.error(this.$t('module.role.warning.selectRole'))
        return
      }
      // 删除提示级别：普通
      new $confirm(this.$t('module.role.warning.confirmDeleteAssignedRole'), this).then(() => {
        let param = {
          orgId: this.orgId,
          roleId: selectedIds
        }
        orgAssignRoleAPI.deleteAssignedRole(param).then(res => {
          this.$message.success({
            content: this.$t('module.orgManage.deleteSuccess'),
            duration: 3
          })
          this.search()
        })
      })
    },
    getSelectedIds() {
      let list = this.$refs['roleTable'].getSelectioned() || []
      let ids = []
      for (let { roleId } of list) {
        ids.push(roleId)
      }
      return ids
    },
    // 数据权限
    setPermissions(data, readOnly) {
      orgAssignRoleAPI
        .queryAccessTypeInfo({
          orgId: this.orgId,
          roleId: data.roleId
        })
        .then(accessInfo => {
          var result = []
          accessInfo.orgNodeVos.some(item => {
            result.push(item.orgId)
          })
          accessInfo.orgNodeVos = result
          this.openDataAccessDialog(data, accessInfo, readOnly)
        })
        .catch(err => {
          this.$message.error({
            content: err.message,
            duration: 3
          })
        })
    },
    // 打开数据权限弹窗
    openDataAccessDialog(data, accessInfo, readOnly) {
      new this.$pageModal(
        DataAccess,
        {
          props: {
            orgData: this.orgData,
            roleId: data.roleId,
            roleName: data.roleName,
            orgName: this.orgName,
            orgId: this.orgId,
            dataAccess: accessInfo,
            readOnly: readOnly
          }
        },
        data => {
          data && this.search()
        }
      )
    },
    // 初始化管理权限
    initManagementType() {
      valueSetAPI.getValueSetByCode('SYS_ROLE_DATA_TYPE').then(data => {
        data.forEach(element => {
          this.managementTypeList[element.vsiKey] = element.vsiValue
        })
      })
    },
    // 初始化用户分配模式
    initAssignmentType() {
      valueSetAPI.getValueSetByCode('SYS_ROLE_ASSIGNMENT_TYPE').then(data => {
        data.forEach(element => {
          this.assignmentTypeList[element.vsiKey] = element.vsiValue
        })
      })
    }
  },
  watch: {
    orgId: {
      handler(newVal, oldVal) {
        this.search(1)
      },
      immediate: true
    }
  },
  directives: {}
}
</script>
